package com.yuchen.ishop.file.service.impl;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.yuchen.ishop.file.service.FileResponse;
import com.yuchen.ishop.file.service.FileService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author Jack Q
 */
@Path("fileService")
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public class FileServiceImpl implements FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    private static final String UPLOADED_TOP_FOLDER = "D:/apache/Apache2/htdocs/ishop";  //文件最上层目录
    private static final String UPLOADED_FILE_IO = "attachment";  //restclient 传入的IO流对应的名称
    private static final String UPLOADED_FILE_TYPE = "fileType";  //restclient 传入的文件类型
    private static final String UPLOADED_FILE_FOLDER = "folder";  //restclient 传入的文件目录


    @POST
    @Path("upload")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public FileResponse upload(final MultipartFormDataInput input) throws IOException {
        FileResponse fileResponse = new FileResponse();
        //Get API input data
        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        //Get file name
        String fileType = getString(uploadForm, UPLOADED_FILE_TYPE);
        logger.debug(fileType);
        String folder = getString(uploadForm, UPLOADED_FILE_FOLDER);
        logger.debug(folder);
        StorageService storageService = new StorageService(UPLOADED_TOP_FOLDER, folder);
        //Get file data to save
        List<InputPart> inputParts = uploadForm.get(UPLOADED_FILE_IO);
        InputPart inputPart = inputParts.get(0);
        try {
            //Use this header for extra processing if required
            @SuppressWarnings("unused")
            MultivaluedMap<String, String> header = inputPart.getHeaders();
            InputStream inputStream = inputPart.getBody(InputStream.class, null);
            String fileName = storageService.createFileName(fileType);
            storageService.saveByteArray(IOUtils.toByteArray(inputStream), fileName);
            fileResponse.setTopFolder(UPLOADED_TOP_FOLDER);
            fileResponse.setPath(folder + "/" + fileName);
            fileResponse.setStatus(true);
            return fileResponse;

        } catch (Exception e) {
            logger.error(e.getMessage());
            fileResponse.setStatus(false);
            return fileResponse;
        }
    }

    @GET
    @Path("delete")
    public FileResponse delete(@QueryParam("fileUrl") String fileUrl) throws IOException {
        FileResponse fileResponse = new FileResponse();
        try {
            String file = UPLOADED_TOP_FOLDER+"/"+fileUrl;
            FileUtils.forceDelete(new File(file));
            fileResponse.setStatus(true);
            return fileResponse;
        } catch (Exception e) {
            logger.error(e.getMessage());
            fileResponse.setStatus(false);
            return fileResponse;
        }
    }

    private String getString(Map<String, List<InputPart>> uploadForm, String key) throws IOException {
        List<InputPart> inputParts = uploadForm.get(key);
        if (null != inputParts && inputParts.size() > 0) {
            InputPart inputPart = inputParts.get(0);
            return inputPart.getBodyAsString();
        }
        return null;
    }
}
